{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 激活扩散\n",
    "from collections import defaultdict\n",
    "import pandas as pd\n",
    "from tqdm import tqdm\n",
    "\n",
    "# 扩散步数\n",
    "step=5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "data=[\n",
    "    ['A','b'],\n",
    "    ['A','d'],\n",
    "    ['B','a'],\n",
    "    ['B','b'],\n",
    "    ['B','c'],\n",
    "    ['C','a'],\n",
    "    ['C','b'],\n",
    "    ['C','d'],\n",
    "    ['D','a'],\n",
    "    ['D','e']\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'A': {'b', 'd'}, 'B': {'a', 'b', 'c'}, 'C': {'a', 'b', 'd'}, 'D': {'a', 'e'}}"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# user->item的映射\n",
    "# key：user\n",
    "# value：item的set\n",
    "train_data = {}\n",
    "\n",
    "for user, item in data:\n",
    "    train_data.setdefault(user,set())\n",
    "    train_data[user].add(item)\n",
    "train_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'b': {'A', 'B', 'C'},\n",
       " 'd': {'A', 'C'},\n",
       " 'a': {'B', 'C', 'D'},\n",
       " 'c': {'B'},\n",
       " 'e': {'D'}}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 建立item_user倒排表\n",
    "item_users = dict()\n",
    "for u, items in train_data.items():\n",
    "    for i in items:\n",
    "        if i not in item_users:\n",
    "            item_users[i] = set()\n",
    "        item_users[i].add(u)\n",
    "item_users"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|███████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 222.82it/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "defaultdict(list,\n",
       "            {'A': ['a', 'c', 'e'],\n",
       "             'B': ['d', 'e'],\n",
       "             'C': ['c', 'e'],\n",
       "             'D': ['b', 'd', 'c']})"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_item = train_data\n",
    "rec_item = defaultdict(list)\n",
    "for u in tqdm(user_item):\n",
    "    # 每个物品第几步被扩散到\n",
    "    visit_step = defaultdict(int)\n",
    "    # 物品扩散到的次数\n",
    "    visit_cnt = defaultdict(int)\n",
    "\n",
    "    user_set = set()\n",
    "    user_set.add(u)\n",
    "    item_set = set()\n",
    "    for k in range(step):\n",
    "        if k % 2 == 0:\n",
    "            # 用户扩散项目\n",
    "            for user in user_set:\n",
    "                for item in user_item[user]:\n",
    "                    if item not in visit_step:\n",
    "                        visit_step[item] = k + 1\n",
    "                    visit_cnt[item] += 1\n",
    "                item_set.update(set(user_item[user]))\n",
    "            user_set = set()\n",
    "        else:\n",
    "            # 项目扩散用户\n",
    "            for item in item_set:\n",
    "                user_set.update(set(item_users[item]))\n",
    "            item_set = set()\n",
    "\n",
    "    res = ((pd.DataFrame(visit_cnt, index=[0]).append(pd.DataFrame(visit_step, index=[1]))).T).sort_values(\n",
    "        [1, 0], ascending=[1, 0]).index.tolist()\n",
    "\n",
    "    rec_item[u] = [i for i in res if i not in user_item[u]]\n",
    "rec_item "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
